import qs from 'qs'

export function getSystem () {
  const userAgent = navigator.appVersion
  const userAgentL = userAgent.toLowerCase()

  /* iOS9 */
  let version, iOS9
  if (userAgentL.indexOf('like mac os x') > 0) {
    const reg = /os [\d._]*/gi
    const info = userAgentL.match(reg)
    version = (info + '').replace(/[^0-9|_.]/ig, '').replace(/_/ig, '.')
  }
  const version_str = version + ''
  if (version_str !== 'undefined' && version_str.length > 0) {
    version = parseInt(version)
    if (version > 12) iOS9 = true
  }
  return {
    // ie: userAgentL.indexOf('msie') > -1 && !userAgentL.indexOf('opera') > -1,
    // gecko: userAgentL.indexOf('gecko') > -1 && !userAgentL.indexOf('khtml') > -1, // 火狐内核
    // webkit: userAgentL.indexOf('applewebkit') > -1, // 苹果、谷歌内核
    // opera: userAgentL.indexOf('opera') > -1 && userAgentL.indexOf('presto') > -1, // opera内核
    // trident: userAgentL.indexOf('trident') > -1, // IE内核
    // mobile: !!userAgent.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
    // mobileDevice: !!userAgentL.match(/iphone|android|phone|mobile|wap|netfront|x11|java|opera mobi|opera mini|ucweb|windows ce|symbian|symbianos|series|webos|sony|blackberry|dopod|nokia|samsung|palmsource|xda|pieplus|meizu|midp|cldc|motorola|foma|docomo|up.browser|up.link|blazer|helio|hosin|huawei|novarra|coolpad|webos|techfaith|palmsource|alcatel|amoi|ktouch|nexian|ericsson|philips|sagem|wellcom|bunjalloo|maui|smartphone|iemobile|spice|bird|zte-|longcos|pantech|gionee|portalmmm|jig browser|hiptop|benq|haier|^lct|320x320|240x320|176x220/i), // 是否为移动终端
    iOS: !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
    iOS9, // ios9+
    android: userAgent.indexOf('Android') > -1 || userAgent.indexOf('Adr') > -1, // android终端或者uc浏览器
    // iPhone: userAgent.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
    // iPad: userAgent.indexOf('iPad') > -1, // 是否iPad
    // qqBrowser : userAgent.indexOf('QQBrowser') > -1, // 是否QQ浏览器
    wechat: userAgent.indexOf('MicroMessenger') > -1, // 是否微信
    // qq: userAgent.match(/QQ\/[0-9]/i) ? true : false, // 是否QQ
    // weibo: userAgent.match(/WeiBo/i) == "weibo", // 微博
    // alipay: userAgent.indexOf('AlipayClient') > -1, // 是否支付宝
    yfd: userAgentL.indexOf('yfdmall_app') > -1
  }
}

export function openApp ({ callback, query, path } = {}) {
  const timeout = 1500 // 超时时间
  let hasApp = true

  /* 拼接路径 */
  let uri
  path = path || '/goodsDetail'
  uri = `yfd://yfdmall:8080${path}`
  if (query) uri = `yfd://yfdmall:8080${path}?${qs.stringify(query)}`

  /* 失败回调 */
  callback = callback || function () {
    window.location.href = 'https://download.yuanfuda933.com/h5/aaa.html'
  }

  /* 打开应用 */
  const time = Date.now()
  const iframe = document.createElement('iframe')
  iframe.setAttribute('src', uri)
  iframe.setAttribute('style', 'display:none')
  document.body.appendChild(iframe)

  /* 校验 */
  setTimeout(t => {
    const current = Date.now()
    if (current - time < timeout + 250) {
      hasApp = false
      return
    } else {
      hasApp = true
    }
    document.body.removeChild(iframe)
  }, timeout)

  /* 超时 */
  setTimeout(t => {
    if (!hasApp) callback && callback()
  }, timeout + 500)
}

export function getUrlQuery (name) {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  const r = window.location.search.substr(1).match(reg)
  if (r != null) {
    return unescape(r[2])
  }
  return null
}
/**
 * key value 转化
 * 黑名单
 * 黑名单属性值可能会出现 = 会影响到切割方法，所以单独处理
 * */
const blackList = ['token', 'sign']
export function parseKeyValue (data) {
  const keyValueArr = data.split('&')
  const keyValueObj = {}
  keyValueArr.map(item => {
    let index = -1
    let keyStr = ''
    blackList.map(black => {
      if (item.indexOf(`${black}=`) > -1) {
        index = item.indexOf(`${black}=`)
        keyStr = `${black}=`
      }
    })
    if (index === 0) {
      const key = item.substring(0, keyStr.length - 1)
      const value = item.substring(keyStr.length, item.length)
      keyValueObj[key] = value
    } else {
      const arr = item.split('=')
      keyValueObj[arr[0]] = arr[1]
    }
  })
  return keyValueObj
}